<template>
    <div>
        <!-- 查询条件 -->
        <div class="queryCriteria">
            <!-- 条件组,插槽 -->
            <slot></slot>
            <!-- 按钮组 -->
            <el-button v-for="(i, n) in btnList" :key="n" :type="i.type" size="small" :icon="i.icon" @click="i.click">
                {{ i.name }}
            </el-button>
        </div>
        <!-- 表格区域 -->
        <!-- 一般文字：{ prop: 'inventory', label: '库存', width: '90' }, -->
        <!-- 图片格式：{ prop: 'profile_picture_url', label: '商品主图', width: '110', isImg: true, height: 50 }, -->
        <!-- 双行文字格式：{ prop: 'information', label: '商品信息', width: '140', doubleRow: true, text1: '货号', text2: '售价' }, -->
        <!-- 开关格式：{ prop: 'listed', label: '是否上架', width: '110', isSwitch: true, }, -->
        <!-- 图片上传格式：{ prop: 'imgs', label: '商品预览图', width: 120, uploadAvatar: true }, -->
        <el-table class="tableCss" v-loading="tableLoading" element-loading-text="Loading..."
            :element-loading-spinner="svg" element-loading-svg-view-box="-10, -10, 50, 50"
            element-loading-background="rgba(122, 122, 122, 0.8)" border :data="paginatedData"
            :default-sort="{ prop: 'date', order: 'descending' }" height="calc(100vh - 275px)"
            :show-overflow-tooltip="true" :cell-style="cellStyle" @selection-change="handleSelectionChange">
            <el-table-column v-if="isSelected" type="selection" :selectable="selectable" width="55" />
            <el-table-column fixed align="center" label="序号" width="60">
                <template #default="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column align="" sortable v-for="(i, n) in columns" :key="n" :prop="i.prop" :label="i.label"
                :formatter="i.formatter" :width="i.width">
                <template #default="scope">
                    <img class="image" v-if="i.isImg && scope.row[i.prop]" :src="scope.row[i.prop]" alt=""
                        draggable="false" :style="`width: ${i.height}px; height: ${i.height}px`"
                        @click="handleImageClick(scope.row[i.prop])" />
                    <img v-else-if="i.isImg && !scope.row[i.prop]" src="@/assets/image/touxing.png" alt=""
                        draggable="false" :style="`width: ${i.height}px; height: ${i.height}px`" />
                    <span v-else-if="i.doubleRow">
                        <span class="doubleRow">{{ i.text1 + ': ' }}</span> {{ scope.row.information?.text1 ?
                            scope.row.information.text1 : '-' }}<br>
                        <span class="doubleRow">{{ i.text2 + ': ' }}</span> {{ scope.row.information?.text2 ?
                            scope.row.information.text2 : '-' }}
                    </span>
                    <el-switch v-else-if="i.isSwitch" active-text="" inactive-text="" active-color="#2fa1f1"
                        inactive-color="#9c9c9c" v-model="scope.row[i.prop]" @change="handleStatusChange(scope.row)" />
                    <div class="imgUp" v-else-if="i.uploadAvatar">
                        <el-upload class="avatar-uploader"
                            :http-request="(options: any) => handleCustomUpload(i, options, scope.row)"
                            :show-file-list="false" :before-upload="beforeAvatarUpload">
                            <img v-if="scope.row[i.prop]" :src="scope.row[i.prop]" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                        <!-- 0719 隐藏删除图片按钮 -->
                        <!-- <el-button v-if="scope.row[i.prop]" type="danger" :icon="Delete" circle size="small"
                            @click="delImg(i, scope.row)" /> -->
                    </div>
                    <div v-else-if="i.order" style="display: flex;justify-content: center;">
                        {{ scope.row[i.prop] }}
                        <el-button style="margin-left: 1rem;" type="primary" :icon="Edit" circle size="small" @click="setOrder(i, scope.row)" />
                    </div>
                    <span v-else>
                        {{ formatCell(i, scope.row) }}
                    </span>
                </template>
            </el-table-column>
            <!-- 固定列 -->
            <el-table-column v-if="isFixedColumn" fixed="right" align="center" label="操作" :width="columnWidth">
                <template #default="scope">
                    <div v-if="isMore">
                        <el-button type="primary" size="small" @click="btnListTable[0].click(scope.row, 1)">{{
                            btnListTable[0].name
                        }}</el-button>
                        <el-popover placement="bottom-start" trigger="hover"
                            :popper-style="{ minWidth: '55px', padding: '10', width: 'auto', cursor: 'pointer' }">
                            <template #reference>
                                <el-button link type="primary" size="small">更多</el-button>
                            </template>
                            <div>
                                <el-button v-for="(i, n) in btnListTable2" :key="n" type="primary" size="small"
                                    @click="i.click(scope.row, 2)">{{ i.name }}</el-button>
                            </div>
                        </el-popover>
                    </div>
                    <div v-else>
                        <!-- 格式:
                        { name: '上架', type: 'primary', click: listed, judgment: true, isShow: ['未上架'], },
                        { name: '下架', type: 'warning', click: removed, judgment: true, isShow: ['已上架'], }, -->
                        <span class="columnBtnList" v-for="(i, n) in btnListTable" :key="n">
                             <view v-if="i.name=='处理' || i.name=='处理详情'">
                                <el-button v-if="i.judgment && i.isShow.includes(scope.row.judData)" :type="i.type"
                                    size="small" @click="i.click(scope.row, 1)" style="width: 4rem;color: #fff;" :color="i.color">{{i.name }}</el-button>
                                <el-button v-else-if="!i.judgment" :type="i.type" size="small"
                                    @click="i.click(scope.row, 1)" style="width: 4rem;color: #fff;">{{i.name }}</el-button>
                            </view>
                            <view v-else>
                                <el-button v-if="i.judgment && i.isShow.includes(scope.row.judData)" :type="i.type"
                                    size="small" @click="i.click(scope.row, 1)" style="color: #fff;"  :color="i.color">{{i.name }}</el-button>
                                <el-button v-else-if="!i.judgment" :type="i.type" size="small"
                                    @click="i.click(scope.row, 1)">{{i.name }}</el-button>
                            </view>
                        </span>
                    </div>
                </template>
            </el-table-column>
            <!-- 最右侧固定列 -->
            <el-table-column v-if="isEndColumns" sortable fixed="right" align="center" :label="EndColumnsData.label"
                :width="EndColumnsData.width">
                <template #default="scope">
                    {{ formatCell(EndColumnsData, scope.row) }}
                </template>
            </el-table-column>
        </el-table>
        <!-- 底部按钮组 -->
        <div class="footerBtnList" v-if="footerBtnList && footerBtnList.length > 0">
            <el-button v-for="(i, n) in footerBtnList" :key="n" :type="i.type" @click="i.click()">{{
                i.name }}</el-button>
        </div>
        <!-- 分页 -->
        <div class="example-pagination-block">
            <div class="demo-pagination-block">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 30, 40, 50]" size="small" :disabled="disabled" :background="background"
                    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
                <!-- 如需靠右显示，在layout里加 -> -->
            </div>
        </div>
        <!-- 模态框 -->
        <el-dialog v-model="dialogVisible" width="60%" top="1vh" center>
            <div class="dialog">
                <img :src="enlargedImageUrl" draggable="false" />
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">关闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang='ts'>
import { ref, computed, defineProps, onMounted, defineEmits, PropType } from 'vue';
import type { UploadProps, TableColumnCtx } from 'element-plus'
import { Delete,Edit } from '@element-plus/icons-vue'
// import type { TableInstance } from 'element-plus'
// import { ElMessage } from 'element-plus';
import { upload, productStyleEdit } from '@/api/seriesMent/index.ts'
import axios from "axios";
const props = defineProps({
    columns: {
        type: Array,
        validator: () => {
            return [];
        }
    },
    endColumnsList: {
        type: Array,
        validator: () => {
            return [];
        }
    },
    paginatedData: {
        type: Array,
        validator: () => {
            return [];
        }
    },
    btnList: {
        type: Array,
        validator: () => {
            return [];
        }
    },
    btnListTable: {
        type: Array,
        validator: () => {
            return [];
        }
    },
    isFixedColumn: {// 是否有操作列
        type: Boolean,
        default: true
    },
    columnWidth: {// 操作列大小
        type: Number,
        default: 130
    },
    isMore: {// 操作列是否有 更多 按钮
        type: Boolean,
        default: true
    },
    footerBtnList: {
        type: Array,
        validator: () => {
            return [];
        }
    },
    isSelected: {// 是否有选择框
        type: Boolean,
        default: false
    },
    isEndColumns: {// 是否有最右侧列
        type: Boolean,
        default: false
    },
    EndColumnsData: {
        type: Object,
        default: () => ({})
    },
    tableLoading: {// 是否加载中
        type: Boolean,
        default: false,
    },
    total: {// 分页 数据总数
        type: Number,
        default: 0
    },
    cellStyle: {
        type: Function as PropType<
            (args: {
                row: any
                column: TableColumnCtx<any>
                rowIndex: number
                columnIndex: number
            }) => Record<string, string>
        >,
        default: () => ({})
    },
});

// 操作列 更多按钮组
const btnListTable2 = ref(props.btnListTable?.slice(1))
// 多选
interface User {
    id: number
    date: string
    name: string
    address: string
}
// 选择的内容
const multipleSelection = ref<User[]>([])
const selectable = (row: User) => ![1, 2].includes(row.id)
const handleSelectionChange = (val: User[]) => {
    multipleSelection.value = val
}
// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const disabled = ref(false)
const background = ref(false)
const enlargedImageUrl = ref('');
const dialogVisible = ref(false);

// 点击图片事件
const handleImageClick = (imageUrl: any) => {
    enlargedImageUrl.value = imageUrl;
    dialogVisible.value = true;
}
const presignedUrl = ref(""); // 用于存储从后端获取的预签名 URL

// 获取预签名 URL
const getPresignedUrl = async (file: any) => {
    try {
        let lastDotIndex = file.name.lastIndexOf('.');
        let name = ''
        if (lastDotIndex !== -1) {
            // 如果找到了最后一个点，截取到该点之前的部分
            name = file.name.substring(0, lastDotIndex);
        }
        cs(name).then((res: any) => {
            // console.log("res", res);
            presignedUrl.value = res; // 存储返回的预签名 URL
            // console.log("111222333", res.indexOf('com/'));
            const index = res.indexOf('com/');
            let abc = ''
            if (index !== -1) {
                abc = res.substring(index + 'com/'.length)
            }
            // var formData = new FormData();
            // formData.append('image', file);
            // const response = fetch('/aly' + abc, {
            //     method: "PUT", // OSS 预签名 URL 使用 PUT 方法上传文件
            //     headers: {
            //         'Content-Type': 'application/octet-stream',
            //         // 如果服务器期望一个特定的签名头，那么请添加它
            //         'Authorization': 'SignedHeadersIfAvailable',
            //         'AccessKey': 'LTAI5tMzrFHsLi3CeyzhnEii'
            //     },
            //     body: file, // 直接上传文件内容
            // });
            // if (response.ok) {
            //     ElMessage.success("文件上传成功");
            // } else {
            //     ElMessage.error("文件上传失败");
            // }

            // 发送PUT请求上传文件
            get(res, file)
        })
        // const response = await axios.get("http://192.168.0.113:8091/url"); // 调用后端接口
    } catch (error) {
        console.error("获取预签名 URL 失败:", error);
        ElMessage.error("获取预签名 URL 失败，请稍后重试");
    }
};
let get = async (res, file) => {
    const response = await fetch(res, {
        method: "PUT", // OSS 预签名 URL 使用 PUT 方法上传文件
        headers: {
            'Content-Type': 'application/octet-stream',
            // 如果服务器期望一个特定的签名头，那么请添加它
            'Authorization': 'SignedHeadersIfAvailable',
            // 'AccessKey': 'LTAI5tMzrFHsLi3CeyzhnEii'
        },
        body: file, // 直接上传文件内容
    });
    if (response.ok) {
        ElMessage.success("文件上传成功");
    } else {
        ElMessage.error("文件上传失败");
    }
}
// 上传图片 开始
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/jpg'
        && rawFile.type !== 'image/bmp' && rawFile.type !== 'image/webp' && rawFile.type !== 'image/gif') {
        ElMessage.error('头像格式只能为jpeg、jpg、png、bmp、webp、gif!!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 4) {
        ElMessage.error('头像大小不能超过4MB!')
        return false
    }
    return true
}
interface iType {
    [key: string]: string
}
interface RowType {
    [key: string]: string
}
const token = localStorage.getItem('token')
const handleCustomUpload = async (i: iType, options: any, row: RowType) => {
    // 如果还没有获取预签名 URL，则先获取
    // if (!presignedUrl.value) {
    //     await getPresignedUrl(options.file);
    // }
    
    try {
        // 1. 创建 FormData 对象
        const formData = new FormData();
        formData.append('file', options.file); // 'file' 是后端接收的参数名
        // console.log(111222, formData);
        // let para = {
        //     // url: '/sc/dpl/v1/admin/productStyle/upload',
        //     file: formData,
        // }
        // upload(para).then((res: any) => {

        // })
        const isD = import.meta.env.MODE === 'development'
            ? '/api'
            : import.meta.env.VITE_APP_BASE_URL

        const endpoint = i.prop === 'cover' 
            ? `${isD}/dpl/v2/admin/products/upload/${row.product_id}` 
            : `${isD}/dpl/v1/admin/productStyle/upload/${row.product_style_id}`;

        const response = await fetch(endpoint, {
            method: "POST",
            body: formData, // 直接上传文件内容
            headers: {
                Authorization: token,
            },
        })
        if (response.ok) {
            try {
                const data = await response.json(); // 解析 JSON 响应
                if (data.code === 200) {
                    // console.log('接口返回数据:', data.data); // 打印返回的数据
                    if(i.prop === 'cover'){
                        row[i.prop] = data.data.cover
                    }else{
                        row[i.prop] = data.data.style_avatar_url
                    }
                    // handleupImg(data.data.style_avatar_url, row)
                    ElMessage.success("文件上传成功");
                }
            } catch (error) {
                row[i.prop] = ''
                console.error('解析响应出错:', error);
            }
        } else {
            ElMessage.error("文件上传失败");
        }
    } catch (error: any) {
        // 5. 处理失败情况
        options.onError(error)
        ElMessage.error('上传失败: ' + (error.response?.data?.message || error.message))
    }
}
// 上传图片 结束
const emits = defineEmits(['pageSize', 'currentPage', 'tabSwitch', 'upImg','handle-order']);
//排序
const setOrder = (i: iType, row: RowType)=>{
    // 触发事件，将列配置和行数据传给父组件
    emits('handle-order', i, row);
} 


// 删除图片
const delImg = (i: iType, row: RowType) => {
    ElMessageBox.confirm('确认删除图片？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        row[i.prop] = ''
    }).catch(() => {
        // 点击取消后，不执行任何操作
    });
}

// 先定义 rowData 类型，包含状态和有效性字段
interface rowData {
    status: string;
    effectiveness: string;
}
// // 设置单元格样式
// const cellStyle = ({ row, column, rowIndex, columnIndex }: {
//     row: rowData
//     column: any
//     rowIndex: number
//     columnIndex: number
// }) => {
//     // 状态列字体颜色
//     // columnIndex 列下标
//     // rowIndex 行下标
//     // row 行
//     // column 列
//     if (row.status == '0') {
//         return { color: "red" };
//     } else if (row.status == '1') {
//         return { color: "green" };
//     }
// }
const cellStyle = ({ row, column, rowIndex, columnIndex }: {
    row: rowData;
    column: { property?: string }; // 明确 column.property 用于判断列
    rowIndex: number;
    columnIndex: number;
}) => {
    // 判断是否是“状态”列
    if (column.property === 'status') {
        if (row.status === '0') {
            return { color: "red" };
        } else if (row.status === '1') {
            return { color: "green" };
        }
    }
    // 判断是否是“有效性”列
    else if (column.property === 'effectiveness') {
        if (row.effectiveness === '1') {
            return { color: "green" };
        } else if (row.effectiveness === '0') {
            return { color: "red" };
        }
    }
    // 其他列或不匹配状态，返回空对象（不改变样式）
    return {};
};

// 分页事件 val: number
const handleSizeChange = () => {
    emits('pageSize', pageSize.value)
}
const handleCurrentChange = () => {
    emits('currentPage', currentPage.value)
}
const handleupImg = (urlData: string, row: object) => {
    emits('upImg', urlData, row)
}
// 计算总数据条数
// const totalData = computed(() => props.paginatedData.length);
// 开关事件
const handleStatusChange = ((row: any) => {
    emits('tabSwitch', row)
})
// 加载中
const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `

// 格式化单元格内容
const formatCell = (column: any, row: string) => {
    return column.formatter ? column.formatter(row) : row[column.prop];
}

onMounted(() => {

});
</script>

<style scoped lang="scss">
.tableCss {
    width: 88%;
    // margin: 1%;
    // margin-left: 15px;
    margin-left: 95px;
    margin-top: 10px;

    .doubleRow {
        color: #bababb;
    }
}

.queryCriteria {
    width: 88%;
    padding: 10px 10px 0 100px;
}

/* 设置表头背景颜色 */
:deep(.el-table__header) th {
    background-color: #9A9A9A !important;
    color: #000 !important;
    font-weight: bold !important;
    font-weight: 500;
}

:deep(.demo-pagination-block) {
    width: 100%;
    // text-align: right;

    .el-pagination__rightwrapper {
        margin: 10px 20px 10px 0;
    }
}

.example-pagination-block {
    width: 88%;
    margin-left: 95px;
    margin-top: 15px;
}

/* 插槽中的表单 */
:deep(.el-form) {
    display: inline-block;

    .el-form-item {
        margin-bottom: 0;
    }
}

.dialog {
    margin: 10px;

    img {
        width: 100%;
    }
}

.dialog-footer {
    text-align: right;
}

.image {
    cursor: pointer;
}

.footerBtnList {
    width: 88%;
    margin-top: 15px;
    margin-left: 95px;
}

.columnBtnList {
    .el-button {
        margin: 0 5px;
    }
}

.imgUp {
    display: flex;
    justify-content: center;
    align-items: center;
}

:deep(.avatar-uploader .avatar) {
    width: 50px;
    height: 50px;
    display: block;
}

:deep(.avatar-uploader) {
    width: 55px;
    display: inline-block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}
</style>